package com.demo;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

public class LinuxCmd {
	private int sitePort = 8080;
	private int site2Port = 8081;
	
	public static void main(String[] args) {
		new LinuxCmd().test();
	}
	
	public void test() {
		try {
			switchSite(true);
			runCommand("nginx -s reload", true);
			
			char c = readKeybord("输入yYnN", 'y', 'Y', 'n', 'N');
			
			switchSite(false);
			runCommand("nginx -s reload", true);
		} catch (Exception ex) {
			log(ex);
		}
	}
	
	public char readKeybord(String info, char ... enableChars) throws IOException {
		boolean showInfo = true;
		while (true) {
			if (showInfo) {
				System.out.println(info);
			}
			char c = (char)System.in.read();
			for (char enableChar : enableChars) {
				if (c == enableChar) {
					return c;
				}
			}
			showInfo = (c != '\r' && c != '\n');
		}
	}
	
	private boolean switchSite(boolean enableSiteOne) {
		boolean isLinux = File.separatorChar == '/';
		if (!isLinux) {
			return true;
		}
		
		File nginxCfgFile = new File("/etc/nginx/conf.d/default.conf");
		if (!nginxCfgFile.exists()) {
			log("未找到nginx配置:" + nginxCfgFile.getPath() + "!");
			return false;
		}
		
		boolean success = true;
		try {
			String content = FileUtils.readFileToString(nginxCfgFile);
			int begin = content.indexOf("#site cluster#");
			int end = -1;
			if (begin > -1) {
				begin += "#site cluster#".length();
				end = content.indexOf("#end#", begin);
			}
			
			if (begin < 0 || end < 0) {
				log("未找到站点1在nginx中的配置");
				return false;
			} else {
				String cfg;
				if (enableSiteOne) {
					cfg = "\n\tserver 127.0.0.1:" + sitePort + "\n\t"
							+ "server 127.0.0.1:" + site2Port + " backup\n\t";
				} else {
					cfg = "\n\tserver 127.0.0.1:" + site2Port + "\n\t";
				}
				String newContent = content.substring(0, begin) + cfg + content.substring(end);
				
				// reload nginx
				if (!StringUtils.equals(content, newContent)) {
					FileUtils.write(nginxCfgFile, newContent);
					runCommand("nginx -s reload", true);
				}
			}
		} catch (Exception ex) {
			success = false;
			log(ex);
		}
		return success;
	}
	
	private boolean runCommand(String cmd, boolean waitOutput) throws IOException, InterruptedException {
		log(cmd);
		Process process = Runtime.getRuntime().exec(cmd);
		if (waitOutput) {
			String str = IOUtils.toString(process.getInputStream());
			if (str != null && str.length() > 0) {
				log(str);
			}
			String err = IOUtils.toString(process.getErrorStream());
			if (err != null && err.length() > 0) {
				log(err);
			}
			int processComplete = process.waitFor();
			return processComplete == 0;
		} else {
			return true;
		}
	}
	
	private void log(String str) {
		System.out.println(str);
	}
	private void log(Exception ex) {
		ex.printStackTrace();
	}
}
